package jgl.vajra.management.part.mine.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.AuthTask;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jgl.vajra.management.R;
import jgl.vajra.management.apshare.AuthResult;
import jgl.vajra.management.bean.AlipayAccountBean;
import jgl.vajra.management.bean.BindAccountBean;
import jgl.vajra.management.bean.WithdrawalAccountBean;
import jgl.vajra.management.databinding.ActivityWithdrawalPageBinding;
import jgl.vajra.management.dialogFragment.WithdrawalBindingDialogFragment;
import jgl.vajra.management.event.BankCardEditEvent;
import jgl.vajra.management.listener.LoginOrBindListener;
import jgl.vajra.management.listener.MyToolbarViewListener;
import jgl.vajra.management.manager.AccountManager;
import jgl.vajra.management.manager.IntentManager;
import jgl.vajra.management.manager.UMLoginManager;
import jgl.vajra.management.part.mine.contract.WithdrawalPageContract;
import jgl.vajra.management.part.mine.viewModel.WithdrawalPageViewModel;
import jgl.vajra.management.utils.RandomUtils;
import jgl.vajra.management.widget.mvvm.factory.CreateViewModel;
import jgl.vajra.management.widget.mvvm.view.BaseMVVMActivity;
import jgl.vajra.management.widget.retrofithelper.utils.AEACCoder;
import jgl.vajra.management.widget.utils.ToastUtils;
import jgl.vajra.management.widget.utils.UIUtils;

@CreateViewModel(WithdrawalPageViewModel.class)
public class WithdrawalPageActivity extends BaseMVVMActivity<WithdrawalPageViewModel, ActivityWithdrawalPageBinding> implements WithdrawalPageContract.View {

    private String balance;
    private String alipayAuth;
    private WithdrawalBindingDialogFragment withdrawalBindingDialogFragment;

    private static final int SDK_AUTH_FLAG = 2;
    private int typeWallet;
    private int type = 0;

    @Override
    public int getLayoutId() {
        return R.layout.activity_withdrawal_page;
    }

    @Override
    public void initView() {
        super.initView();
        mBinding.setView(this);
        typeWallet = getIntent().getIntExtra("type", 0);

        mBinding.toolbar.setMyToolbarViewListener(new MyToolbarViewListener() {
            @Override
            public void onRightTextClick() {
                super.onRightTextClick();
                IntentManager.toWithdrawalRecordActivity(WithdrawalPageActivity.this);
            }
        });


        balance = getIntent().getStringExtra("balance");
        mBinding.tvBalance.setText("当前零钱余额" + balance + "元");

        UMLoginManager.getInstance().setLoginOrBindListener(new LoginOrBindListener() {
            @Override
            public void onSuccess(Map<String, String> accountMap, String type) {
                if (type.equals("wx_app")) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("type", 2);//1-银行，2-微信，3-支付宝
                    map.put("accountNumber", accountMap.get("openid"));
                    map.put("name", accountMap.get("name"));

                    mViewModel.bindBankCardData(map);
                }
            }

            @Override
            public void failure() {
                ToastUtils.showShort("取消了");
            }
        });

        requestNetData();
    }

    private void requestNetData() {
        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);

        mViewModel.getBindAccountData(map);

        mViewModel.getAlipayAuthData(map);
    }


    //编辑银行卡
    @Override
    public void onEditNow() {
        IntentManager.toBankCardActivity(this);
    }

    //绑定银行卡
    @Override
    public void onBindNow(String accountNumberYhk) {
        IntentManager.toBankCardEditActivity(this);
    }

    //微信换绑
    @Override
    public void unboundWx() {
//        UMLoginManager.getInstance().umengDeleteOauthWx(this);
        UMLoginManager.getInstance().umengLoginWx(this);
    }

    //绑定微信
    @Override
    public void onBindWx() {
        UMLoginManager.getInstance().umengLoginWx(this);
    }

    //绑定支付宝
    @Override
    public void onBindZfb() {
        // authInfo 的生成包括签名逻辑。故生成过程请务必在服务端进行。
        String authInfo = alipayAuth;
        // 对授权接口的调用需要异步进行。
        Runnable authRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造AuthTask 对象
                AuthTask authTask = new AuthTask(WithdrawalPageActivity.this);
                // 调用授权接口
                // AuthTask#authV2(String info, boolean isShowLoading)，
                // 获取授权结果。
                Map<String, String> result = authTask.authV2(authInfo, true);
                // 将授权结果以 Message 的形式传递给 App 的其它部分处理。
                // 对授权结果的处理逻辑可以参考支付宝 SDK Demo 中的实现。
                Message msg = new Message();
                msg.what = SDK_AUTH_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread authThread = new Thread(authRunnable);
        authThread.start();

    }

    //选择银行卡
    @Override
    public void onChoiceYhk(int type, String accountNumber) {
        if (TextUtils.isEmpty(accountNumber)) {
            return;
        }
        this.type = type;
        mBinding.ivYhk.setSelected(true);
        mBinding.ivWx.setSelected(false);
        mBinding.ivZfb.setSelected(false);
    }

    //选择微信
    @Override
    public void onChoiceWx(int type, String accountNumber) {
        if (TextUtils.isEmpty(accountNumber)) {
            return;
        }
        this.type = type;
        mBinding.ivYhk.setSelected(false);
        mBinding.ivWx.setSelected(true);
        mBinding.ivZfb.setSelected(false);
    }

    //选择支付宝
    @Override
    public void onChoiceZfb(int type, String accountNumber) {
        if (TextUtils.isEmpty(accountNumber)) {
            return;
        }
        this.type = type;
        mBinding.ivYhk.setSelected(false);
        mBinding.ivWx.setSelected(false);
        mBinding.ivZfb.setSelected(true);
    }

    //支付宝解绑
    public void unboundZfb() {
        onBindZfb();

      /*  if (withdrawalBindingDialogFragment == null)
            withdrawalBindingDialogFragment = new WithdrawalBindingDialogFragment();
        withdrawalBindingDialogFragment.show(this.getSupportFragmentManager());*/
    }

    //确认提现
    @Override
    public void onDetermine() {

        if (type == 0) {
            ToastUtils.showShort("请选择提现方式");
            return;
        }

        String amount = mBinding.etNum.getText().toString().trim();
        if (TextUtils.isEmpty(amount)) {
            ToastUtils.showShort("提现金额不能为空");
            return;
        }

        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);
        map.put("amount", AEACCoder.encrypt(amount + "&&" + RandomUtils.getRandom()));
        map.put("type", type);
        map.put("reverseType", typeWallet);

        mViewModel.incomeWithdrawData(map);
    }

    @Override
    public void returnBindAccountData(List<BindAccountBean> data) {
        WithdrawalAccountBean bean = new WithdrawalAccountBean();
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).type == 1) {
                bean.typeYhk = data.get(i).type;
                bean.accountNumberYhk = data.get(i).accountNumber;
                bean.nameYhk = data.get(i).name;
            } else if (data.get(i).type == 2) {
                bean.typeWx = data.get(i).type;
                bean.accountNumberWx = data.get(i).accountNumber;
                bean.nameWx = data.get(i).name;
            } else if (data.get(i).type == 3) {
                bean.typeZfb = data.get(i).type;
                bean.accountNumberZfb = data.get(i).accountNumber;
                bean.nameZfb = data.get(i).name;
            }
        }

        mBinding.setData(bean);

    }

    @Override
    public void returnAlipayAuthData(String alipayAuth) {
        this.alipayAuth = alipayAuth;
    }

    @Override
    public void returnAlipayAccountData(AlipayAccountBean data) {
        Map<String, Object> map = new HashMap<>();

        map.put("type", 3);//1-银行，2-微信，3-支付宝
        map.put("accountNumber", AEACCoder.encrypt(data.userId));
        map.put("name", data.nickName);

        mViewModel.bindBankCardData(map);
    }

    @Override
    public void returnBindBankCardData() {
        requestNetData();
    }

    @Override
    public void returnIncomeWithdrawData() {
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMLoginManager.getInstance().onActivityResult(requestCode, resultCode, data, this);
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_AUTH_FLAG: {
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        ToastUtils.showShort("授权成功");
                        Logger.d("授权成功" + authResult.getResult());
                        String[] resultValue = authResult.getResult().split("&");
                        for (String value : resultValue) {
                            if (value.startsWith("auth_code")) {
                                String authCode = AuthResult.removeBrackets(AuthResult.getValue("auth_code=", value), true);
                                Logger.d("授权成功" + authCode);

                                Map<String, Object> map = new HashMap<>();
                                map.put("Authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);
                                map.put("authorCode", AEACCoder.encrypt(authCode));//支付宝授权号
                                mViewModel.getAlipayAccountData(map);
                            }
                        }
                    } else {
                        // 其他状态值则为授权失败
                        ToastUtils.showShort("授权失败");
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    @Override
    protected boolean isRegisterEvent() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBankCardEditEvent(BankCardEditEvent event) {
        requestNetData();
    }
}
